package com.xunshibao.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.xunshibao.entity.info.TutorInfo;

public class ReflectionUtil {
	/**
	 * 将source和destination的属性进行比较，如果source和destination的属性值不相等，则用
	 * source的值覆盖掉destination的值
	 * 
	 * @param source
	 * @param desination
	 * @return
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static int copyChangeValue(Object source, Object destination, List<String> excludes) {
		Class clz = source.getClass();
		Field[] fields = clz.getDeclaredFields();
		if (fields != null) {
			int result = 0;
			if (excludes == null) {
				excludes = Collections.emptyList();
			}
			Class[] setMParam = new Class[] {};
			Class[] getMParam = new Class[1];
			String fieldName;
			String getName;
			String setName;
			Method getMethod;
			Method setMethod;
			Object[] getParam = new Object[] {};
			Object[] setParam = new Object[1];
			Object srcV;
			Object desV;
			for (Field f : fields) {
				try {
					fieldName = f.getName();
					if (Modifier.isStatic(f.getModifiers()) || excludes.contains(fieldName)) {
						continue;
					}
					fieldName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
					getName = "get" + fieldName;
					setName = "set" + fieldName;
					getMethod = clz.getMethod(getName, setMParam);
					getMParam[0] = f.getType();
					setMethod = clz.getMethod(setName, getMParam);
					// 取值
					setParam[0] = srcV = getMethod.invoke(source, getParam);
					desV = getMethod.invoke(destination, getParam);
					if (srcV != null && desV != null) {
						if (!srcV.equals(desV)) {
							// 设值
							setMethod.invoke(destination, setParam);
							result++;
						}
					} else {
						if(srcV == null && desV != null) {
							setMethod.invoke(destination, srcV);
							result++;
						} else if(srcV != null && desV == null) {
							setMethod.invoke(destination, srcV);
							result++;
						}
					}
				} catch (Exception e) {
					return -1;// 复制失败
				}
			}
			return result;
		}
		return 0;
	}

	public static int copyChangeValue(Object source, Object destination) {
		return copyChangeValue(source, destination, null);
	}

	public static void main(String[] args) {
		TutorInfo source = new TutorInfo(1l, 2l, 2, "hahah");
		TutorInfo desination = new TutorInfo(2l, 2l, 2, "huohuo");
		int result = ReflectionUtil.copyChangeValue(source, desination, Arrays.asList("id"));
		System.out.println(result);
		System.out.println("1");
	}
}
